package com.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MainUtlis {
	/**获取请求头*/
	public static void test3(HttpServletRequest request) {
        Enumeration<String> e = request.getHeaderNames();
        while(e.hasMoreElements()){
            String headerName = e.nextElement();//透明称
            Enumeration<String> headerValues = request.getHeaders(headerName);
            while(headerValues.hasMoreElements()){
                System.out.println(headerName+":"+headerValues.nextElement());
            }
        }
    }
	/**获取ip*/
	public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
	
	/**
	 * 当前时间
	 * */
	public static String getNowTime() {
		Date now = new Date(); 
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
		String time = dateFormat.format( now ); 
		return time;
	}
	
	/**
	 * 操作监控
	 * */
	public static void Trace (String info) {
		Date now = new Date(); 
		SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");//可以方便地修改日期格式
		String time = dateFormat2.format( now ); 
		String time2 = getNowTime();
		info = time2 +info;
		File file = new File("G:/web操作监控/"+time+".txt");//每天记录在不同的文件中
		try {
			FileOutputStream out = new FileOutputStream(file, true);
			StringBuffer sb = new StringBuffer();
			sb.append(info + "\n");
			out.write(sb.toString().getBytes("utf-8"));
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @Description: 实体转化成json
	 * @param: @param obj 实体
	 * @param: @return  json格式的字符串    
	 * @date: 2018年8月29日
	 */
	public static String toJSON(Object obj) {
	    ObjectMapper om = new ObjectMapper();
	    try {
	        String json = om.writeValueAsString(obj);
	        return json;
	    } catch (JsonProcessingException e) {
	        e.printStackTrace();
	    }
	    return null;
	}
}
